import Layout from "@/layout";
import React, {useState} from "react";
import {useLayout} from "@/layout/LayoutProvider";
import styled from "@emotion/styled";
import {Button, Menu, MenuItem} from '@mui/material';
import {useTranslation} from "react-i18next";
import {useLogout} from '@/services/user'
import {useRoot} from '../../RootProvider'
import i18n from "i18next";
import viteLogo from '/vite.svg'

const LogContainer = styled('div')(({ownerState}) => ({
    height: 64,
    display: 'flex',
    padding: "0px 10px",
    alignItems: 'center',
    justifyContent: 'center',
    textAlign: 'center',
}))
const Logo = () => {
    return <LogContainer>
        <img src={viteLogo}/>
    </LogContainer>
}
const Right = () => {
    const {mutate} = useLogout((data)=>{
        if(data.code === 200){
            setAnchorEl(null)
            localStorage.removeItem('permissions')
            localStorage.removeItem('token')
            window.open('/login', '_self')
        }
    })
    const {t} = useTranslation();
    const {state, setState} = useLayout()
    const {language} = state
    const [anchorEl, setAnchorEl] = React.useState(null);
    const open = Boolean(anchorEl);
    const handleClick = (event) => {
        setAnchorEl(event.currentTarget);
    };
    const handleClose = () => {
        setAnchorEl(null)
    }
    const logoutAction = () => {
        mutate()
    }
    return <div>
        <Button variant="outlined" onClick={() => {
            i18n.changeLanguage(language === 'zh' ? 'en' : 'zh')
            setState({
                language: language === 'zh' ? 'en' : 'zh'
            })
        }}>{`${language === 'zh' ? '英文' : '中文'}`}</Button>
        <Button onClick={handleClick}>{`${t('hello')},admin`}</Button>
        <Menu
            anchorEl={anchorEl}
            open={open}
            onClose={handleClose}>
            <MenuItem  onClick={logoutAction}>{t('logout')}</MenuItem>
        </Menu>
    </div>
}
const Home = () => {
    const {layout:mode} = useRoot()
    const normalLayoutOptions = {
        headerProps: {
            title: <h2>vite-react</h2>,
            right: <Right/>
        },
        sliderProps: {
            logo: <Logo/>
        },
        menuProps: {
            items:undefined,
        },
        contentProps: {}
    }
    const fixedLayoutOptions = {
        headerProps: {
            left: <Logo/>,
            right: <Right/>
        },
    }
    const mixedLayoutOptions = {
      headerProps: {
        left: <Logo/>,
        title: <h2>vite-react</h2>,
        right: <Right/>
      }
    }
    if(mode === 'fixed'){
        return <Layout mode={mode} {...fixedLayoutOptions}/>
    }else if(mode === 'mixed'){
      return <Layout mode={mode} {...mixedLayoutOptions}/>
    }else{
        return <Layout mode={mode} {...normalLayoutOptions}/>
    }
}
export default Home
